package com.boot.security.server.service.impl.mffl.MfflContract;

import com.boot.security.server.dao.UserDao;
import com.boot.security.server.dao.mffl.*;
import com.boot.security.server.model.SysUser;
import com.boot.security.server.model.mffl.*;
import com.boot.security.server.model.mffl.Vo.MfflContractVo;
import com.boot.security.server.service.impl.mffl.Lawyerservicepeoplenumber.LawyerservicepeoplenumberService;
import com.boot.security.server.service.impl.mffl.LwyerPersonalService.LwyerPersonalService;
import com.boot.security.server.service.impl.mffl.MfflLawyerComment.MfflLawyerCommentService;
import com.boot.security.server.service.impl.mffl.Mfflpublic.publicService;
import com.boot.security.server.service.impl.mffl.WXPay.WXPayService;
import com.boot.security.server.utils.UserUtil;
import com.boot.security.server.utils.mffl.ProjectUtil;
import com.boot.security.server.utils.mffl.ReturnBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import com.boot.security.server.service.impl.mffl.MfflSystemMessages.MfflSystemMessagesImpl;

import java.util.*;

/**
 * 合同服务
 */
@Service
public class MfflContractService {
    //合同dao
    @Autowired
    private MfflContractDao mfflContractDao;

    //服务
    @Autowired
    MfflServiceDao mfflservicedao;

    //服务类型
    @Autowired
    MfflTypeDao mffltypedao;


    //用户表
    @Autowired
    MfflUserDao mffluserdao;

    //律师收费标准
    @Autowired
    private LwyerPersonalService lwyerPersonalservice;

    //订单
    @Autowired
    private MfflOrderDao mfflOrderDao;

    //微信支付
    @Autowired
    private WXPayService wxpayservice;

    //支入支出表
    @Autowired
    private MfflProfitDao mfflProfitDao;

    //系统表
    @Autowired
    UserDao userdao;

    //评论
    @Autowired
    MfflLawyerCommentService mfflLawyercommentservice;

    //退款表
    @Autowired
    MfflRefundDao mfflRefundDao;

    //服务人数
    @Autowired
    LawyerservicepeoplenumberService LawyerservicepeoplenumberService;

    //推送
    @Autowired
    MfflSystemMessagesImpl MfflSystemMessagesImpl;
    //公共功能
    @Autowired
    private publicService publicService;


    //配置微信支付随机数
    @Value("${Pay.attach}")
    private String attach;

    /**
     * 合同发布
     *
     * @param serviceId       服务id
     * @param typeId          服务类型id
     * @param email           收件邮箱
     * @param content         备注
     * @param imageUrl        图片地址(json)
     * @param serviceLawyerId 服务律师id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ReturnBean contractSave(Integer serviceId, Integer typeId, String email, String content, String imageUrl, Integer serviceLawyerId) throws Exception{
        ReturnBean returnBean = new ReturnBean();
        //4合同审核，5合同定制
        Integer service = serviceId == 0 ? 4 : 5;
        //类型是否存在
        MfflType Typ = mffltypedao.getByTypeId(typeId, service);
        if (Typ == null) {
            returnBean.setReturnBean("110");
            return returnBean;
        }

        //律师是否存在
        mfflUserSimple lawyer = mffluserdao.getLawyer(serviceLawyerId);
        if (lawyer == null) {
            returnBean.setReturnBean("116");
            return returnBean;
        }

        //查看律师是否通过认证
        if (lawyer.getLawyerinspect() != 1) {
            returnBean.setReturnBean("137");
            return returnBean;
        }

        //查看律师收费标准
        MfflLwyerPersonalService mps = lwyerPersonalservice.getLawyerServiceMoney(serviceLawyerId, service);
        if (mps == null) {
            returnBean = new ReturnBean();
            returnBean.setReturnBean("112");
            return returnBean;
        }

        //获取当前用户
        SysUser sysUser = userdao.getById(UserUtil.getLoginUser().getId());
        //查询用户
        MfflUser byId = mffluserdao.getByUserId(sysUser.getId());

        //未设置手机号
        if (sysUser.getPhone() == null) {
            returnBean.setReturnBean("121");
            return returnBean;
        }

        if (byId.getIdentity() == 1) {
            returnBean.setReturnBean("122");
            return returnBean;
        }
        try {
            //合同
            MfflService mfce = mfflservicedao.getById(service.longValue());
            MfflContract mct = new MfflContract();
            mct.setUserid(sysUser.getId().intValue());
            mct.setNumber(sysUser.getPhone());
            mct.setServiceId(service);
            mct.setServiceName(mfce.getName());
            mct.setName("");
            mct.setServiceName(service == 4 ? "合同审核" : "合同定制");
            mct.setFile("");
            mct.setImageUrl(imageUrl == null ? "" : imageUrl);
            mct.setContent(content == null ? "" : content);
            mct.setEmail(email);
            mct.setMoney(mps.getMoney());
            mct.setServiceLawyerId(lawyer.getId().intValue());
            mct.setPayId(0);
            mct.setPayNumber("");
            String payMerchantNumber = ProjectUtil.payMerchantNumber(); //获取商户订单号
            mct.setPayMerchantNumber(payMerchantNumber);
            mct.setPayState(0);//支付状态:0.待支付1.已支付2.已退款3.申请退款
            mct.setState(0);//订单状态:0.发布成功1.已接单2.拒绝接单3.已发货4.完成交易5.已撤销订单6.超时接单撤销,自动退款7.已退款
            mct.setType(Typ.getId().intValue());
            mct.setTypeName(Typ.getName());
            Date date = new Date();
            mct.setCreateTime(date);
            mct.setUpdateTime(date);
            mct.setDeleteState(1);
            mct.setDeleteTime(date);
            mct.setPaymentTime(date);
            mct.setConfirmTime(ProjectUtil.getinitialTime()); //初始时间
            mct.setCourierCompanyId(0);
            mct.setCourierNumber("");
            mct.setSender("");
            mct.setOriginatingPlace("");
            mct.setSenderPhone("");
            mct.setAddRessee("");
            mct.setRecipientPhoneNumber("");
            mct.setAddress("");
            mct.setLaywerConten("");
            mct.setLawyerimage("");
            mct.setLawyerfile("");
            mct.setCommentState(0);//是否评论状态0未评论1评论
            mct.setLawyerphone(lawyer.getPhone());
            mct.setRefuseTime(ProjectUtil.getinitialTime());
            int contractsave = mfflContractDao.save(mct);

            //创建订单
            MfflOrder mfflOrder = new MfflOrder();
            mfflOrder.setPayNumber("");
            mfflOrder.setPayMerchantNumber(payMerchantNumber);  //获取商户订单号
            mfflOrder.setServierId(service);                    //4合同审核，5合同定制
            mfflOrder.setServiceName(service == 4 ? "合同审核" : "合同定制");                  //服务名称
            mfflOrder.setMoney(mps.getMoney());                 //金额
            mfflOrder.setUserid(sysUser.getId().intValue());
            mfflOrder.setCreateTime(date);
            mfflOrder.setUpdtaeTime(date);
            mfflOrder.setDeleteTime(date);
            mfflOrder.setDeleteStae(1);                         //是否删除(0删除,1正常)
            mfflOrder.setTypeid(typeId);                        //类型
            mfflOrder.setState(0);                              //0待支付，1支付，2退款
            Long ProductId = mct.getId();
            mfflOrder.setProductId(ProductId.intValue());       //订单关联
            int saveOrderDao = mfflOrderDao.save(mfflOrder);

            //合同关联订单
            MfflContract mfll = new MfflContract();
            mfll.setId(mct.getId());
            mfll.setPayId(mfflOrder.getId().intValue());
            mfflContractDao.update(mfll);

            returnBean = new ReturnBean();
            if (contractsave == 1 && saveOrderDao == 1) {
                returnBean.setReturnBean("200");
                returnBean.setDatas(payMerchantNumber);
            } else {
                returnBean.setReturnBean("105");
            }
            return returnBean;
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("发布异常");
        }
    }


    /**
     * 查询订单状态
     * <p>
     * 如果查询微信订单为已支付并且本地order未改变，则修改状态
     *
     * @param payMerchantNumber
     * @return
     */
    @Transactional
    public ReturnBean orderquery(String payMerchantNumber) throws Exception {
        ReturnBean returnbean = new ReturnBean();
        try {
            Map<String, String> orderquery = wxpayservice.orderquery(payMerchantNumber);
            MfflOrder Order = mfflOrderDao.getByPaymerchantNumberlocking(payMerchantNumber);
            if (!(orderquery.containsKey("trade_state") && orderquery.get("trade_state").equals("SUCCESS")) || Order.getState() == 0) {
                MfflOrder mfflOrder = new MfflOrder();
                mfflOrder.setId(Order.getId());
                mfflOrder.setState(5);//支付中
                mfflOrder.setUpdtaeTime(new Date());
                mfflOrderDao.update(mfflOrder);
                returnbean.setDatas(orderquery);
                return returnbean;
            }

            //订单操作
            String payNumber = orderquery.get("transaction_id");
            //合同状态
            MfflContractVo MfflContract = mfflContractDao.getById(Order.getProductId().longValue());
            //如果状态未改变则改变状态
            if (MfflContract.getPayState() == 0 || (Order.getState() == 0 || Order.getState() == 5)) {
                //创建一个实体，防止在修改过程中其他信息改变的风险
                MfflOrder mfflOrder = new MfflOrder();
                mfflOrder.setId(Order.getId());
                mfflOrder.setPayNumber(payNumber);
                mfflOrder.setUpdtaeTime(new Date());
                mfflOrder.setState(1);
                mfflOrderDao.update(mfflOrder);


                //创建一个实体，防止在修改过程中其他信息改变的风险
                MfflContract ml = new MfflContract();
                ml.setId(MfflContract.getId());
                if (MfflContract.getPayId() == null || MfflContract.getPayId() == 0) {
                    ml.setPayId(mfflOrder.getId().intValue());
                }
                ml.setPayNumber(payNumber);
                //ml.setState(1);   //订单状态:0.发布成功1.已接单2.拒绝接单3.已发货4.完成交易5.已撤销订单6.超时接单撤销,自动退款7.已退款
                ml.setPayState(1);//支付状态:0.待支付1.已支付2.已退款3.申请退款
                ml.setPaymentTime(new Date());

                //确认拒绝服务时间（律师多久无反应后，视为拒绝服务）
                MfflService byId = mfflservicedao.getById((long) MfflContract.getServiceId());
                long t1 = System.currentTimeMillis();
                long t2 = Long.valueOf(byId.getRefuseTime());
                Date dateTime = new Date();
                dateTime.setTime(t1 + t2);
                ml.setRefuseTime(dateTime);
                mfflContractDao.update(ml);

                //用户支出信息
                //金额来自律师个人服务项目，扣点来自服务表
                //double points = ProjectUtil.Points(mll.getMoney(), ms.getPoints());
                //插入 支入支出表
                List<MfflProfit> byOrderId = mfflProfitDao.getOrderId(mfflOrder.getId().intValue());
                if (byOrderId.size() == 0) {
                    MfflProfit mp = new MfflProfit();
                    mp.setOrderId(mfflOrder.getId().intValue());
                    mp.setUserId(MfflContract.getUserid()); //用户id
                    mp.setServciceName(MfflContract.getServiceName());
                    mp.setState(0);               //0支出，1收益,
                    mp.setMoney(MfflContract.getMoney());  //支出不扣点
                    mp.setSettlement(1);          //0未结算，1已经算
                    mp.setCreateTime(new Date());
                    mp.setSettlementTime(new Date());
                    mp.setDeduction(0.0);
                    mp.setUpdateTime(new Date());
                    mfflProfitDao.save(mp);

                    //律师支出
                    MfflProfit mlp = new MfflProfit();
                    mlp.setOrderId(Order.getId().intValue());
                    mlp.setUserId(MfflContract.getServiceLawyerId()); //律师id
                    mlp.setServciceName(MfflContract.getServiceName());
                    mlp.setState(1);               //0支出，1收益,
                    mlp.setMoney(MfflContract.getMoney());   //律师收益显示已扣点金额
                    mlp.setSettlement(0);          //0未结算，1已经算
                    mlp.setCreateTime(new Date());
                    mlp.setSettlementTime(new Date());
                    mlp.setDeduction(0.0);   //平台扣点金额
                    mlp.setUpdateTime(new Date());
                    mfflProfitDao.save(mlp);
                    MfflSystemMessagesImpl.sendMessage(publicService.MessageModel("[合同服务]一条新的律师函业务", MfflContract.getPayMerchantNumber()), MfflContract.getType().toString(), MfflContract.getId().intValue(), MfflContract.getServiceLawyerId());
                }
                return returnbean;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception(e.getMessage());
        }
        returnbean.setReturnBean("141");
        return returnbean;
    }

    //微信支付
    public ReturnBean ServicePay(String payMerchantNumber, String notifyurl) {
        MfflContract getpaymerchantnumber = mfflContractDao.getpaymerchantnumber(payMerchantNumber);
        if (getpaymerchantnumber == null) {
            ReturnBean returnbean = new ReturnBean();
            returnbean.setReturnBean("106");
            returnbean.setMessage("当前商户订单号对应的，合同服务不存在");
            return returnbean;
        }
        ReturnBean returnBean = wxpayservice.WXPay(notifyurl, getpaymerchantnumber.getServiceName(), payMerchantNumber);
        if ("123".equals(returnBean.getErrCode())) {
            //订单号重复支付修改订单号，修改数据订单号
            //修改合同订单号  修改order订单号
            //订单操作
            MfflOrder Order = mfflOrderDao.getBypaymerchantnumber(payMerchantNumber);
            //合同
            MfflContract MfflContract = mfflContractDao.getById(Order.getProductId().longValue());

            //重新生成订单号
            String newpayMerchantNumber = ProjectUtil.payMerchantNumber();

            //创建一个实体，防止在修改过程中其他信息改变的风险
            MfflOrder mfflOrder = new MfflOrder();
            mfflOrder.setId(Order.getId());
            mfflOrder.setPayMerchantNumber(newpayMerchantNumber);
            mfflOrder.setUpdtaeTime(new Date());
            mfflOrderDao.update(mfflOrder);

            //创建一个实体，防止在修改过程中其他信息改变的风险
            MfflContract ml = new MfflContract();
            ml.setId(MfflContract.getId());
            ml.setPayMerchantNumber(newpayMerchantNumber);
            ml.setUpdateTime(new Date());
            mfflContractDao.update(ml);
            ReturnBean returnbean = new ReturnBean();
            returnbean.setReturnBean("142");
            returnbean.setDatas(new HashMap<String, String>() {{
                put("newpayMerchantNumber", newpayMerchantNumber);
            }});
            return returnbean;
        }
        return returnBean;
    }


    //微信支付回调
    @Transactional(rollbackFor = Exception.class)
    public boolean WechatPayCallback(Map<String, String> map) throws Exception {
        System.out.println("访问回调");
        System.out.println(map);
        String paymerchantnumber = map.get("out_trade_no");//商户订单号
        String payNumber = map.get("transaction_id");      //交易单号
        String nonceStr = map.get("attach");      //随机数
        //验证随机数
        if (!attach.equals(nonceStr)) {
            System.out.println("验证随机数不通过");
            return false;
        }
        try {
            //订单操作
            MfflOrder Order = mfflOrderDao.getBypaymerchantnumber(paymerchantnumber);
            //合同
            MfflContract MfflContract = mfflContractDao.getById(Order.getProductId().longValue());
            //如果已支付返回true
            if (MfflContract.getPayState() != 0 && !(Order.getState() == 0 || Order.getState() == 5)) {
                return true;
            }
            //创建一个实体，防止在修改过程中其他信息改变的风险
            MfflOrder mfflOrder = new MfflOrder();
            mfflOrder.setId(Order.getId());
            mfflOrder.setPayNumber(payNumber);
            mfflOrder.setUpdtaeTime(new Date());
            mfflOrder.setState(1);
            mfflOrderDao.update(mfflOrder);


            //创建一个实体，防止在修改过程中其他信息改变的风险
            MfflContract ml = new MfflContract();
            ml.setId(MfflContract.getId());
            if (StringUtils.isEmpty(MfflContract.getPayId()) || MfflContract.getPayId() == 0) {
                ml.setPayId(mfflOrder.getId().intValue());
            }
            ml.setPayNumber(payNumber);
            //ml.setState(1);   //订单状态:0.发布成功1.已接单2.拒绝接单3.已发货4.完成交易5.已撤销订单6.超时接单撤销,自动退款7.已退款
            ml.setPayState(1);//支付状态:0.待支付1.已支付2.已退款3.申请退款
            Date date = new Date();
            ml.setPaymentTime(date);

            //确认拒绝服务时间（律师多久无反应后，视为拒绝服务）
            MfflService byId = mfflservicedao.getById((long) MfflContract.getServiceId());
            long t1 = System.currentTimeMillis();
            long t2 = Long.valueOf(byId.getRefuseTime());
            Date dateTime = new Date();
            dateTime.setTime(t1 + t2);
            ml.setRefuseTime(dateTime);
            mfflContractDao.update(ml);

            //用户支出信息
            //金额来自律师个人服务项目，扣点来自服务表
            //double points = ProjectUtil.Points(mll.getMoney(), ms.getPoints());
            //插入 支入支出表
            List<MfflProfit> byOrderId = mfflProfitDao.getOrderId(mfflOrder.getId().intValue());
            if (byOrderId.size() == 0) {
                MfflProfit mp = new MfflProfit();
                mp.setOrderId(mfflOrder.getId().intValue());
                mp.setUserId(MfflContract.getUserid()); //用户id
                mp.setServciceName(MfflContract.getServiceName());
                mp.setState(0);               //0支出，1收益,
                mp.setMoney(MfflContract.getMoney());  //支出不扣点
                mp.setSettlement(1);          //0未结算，1已经算
                mp.setCreateTime(date);
                mp.setSettlementTime(date);
                mp.setDeduction(0.0);
                mp.setUpdateTime(date);
                mfflProfitDao.save(mp);

                //律师支出
                MfflProfit mlp = new MfflProfit();
                mlp.setOrderId(Order.getId().intValue());
                mlp.setUserId(MfflContract.getServiceLawyerId()); //律师id
                mlp.setServciceName(MfflContract.getServiceName());
                mlp.setState(1);               //0支出，1收益,
                mlp.setMoney(MfflContract.getMoney());   //律师收益显示已扣点金额
                mlp.setSettlement(0);          //0未结算，1已经算
                mlp.setCreateTime(date);
                mlp.setSettlementTime(date);
                mlp.setDeduction(0.0);   //平台扣点金额
                mlp.setUpdateTime(date);
                mfflProfitDao.save(mlp);
            }
            //推送
            MfflSystemMessagesImpl.sendMessage(publicService.MessageModel("[合同服务]一条新的合同业务", MfflContract.getPayMerchantNumber()), MfflContract.getServiceId().toString(), MfflContract.getId().intValue(), MfflContract.getServiceLawyerId());
        } catch (Exception e) {
            e.printStackTrace();
            //防止意外错误
            throw new Exception("错误");
        }
        return true;
    }


    /**
     * 律师发送邮件
     *
     * @param id           律师函id
     * @param laywerConten 律师意见
     * @param lawyerimage  律师意见图片
     * @return
     */
    @Transactional
    public ReturnBean LawyerSendMail(Integer id, String laywerConten, String lawyerimage) {
        ReturnBean returnbean = new ReturnBean();
        //获取当前用户
        SysUser sysUser = UserUtil.getLoginUser();
        MfflUser mffluser = mffluserdao.getByUserId(sysUser.getId());
        //判断各项信息是否正常

        //合同是否存在
        MfflContract mll = mfflContractDao.getById(id.longValue());
        if (mll == null) {
            return new ReturnBean("201", "合同不存在");
        }

        if (mll.getEmail() == null) {
            returnbean.setReturnBean("120");
            return returnbean;
        }

        //判断当前律师是否，是负责当前律师函的律师

        if (mffluser.getIdentity() != 1) {
            return new ReturnBean("201", "当前用户不是律师");
        }

        if (mll.getServiceLawyerId() != sysUser.getId().intValue()) {
            return new ReturnBean("201", "当前律师不是,负责此律师函的律师");
        }

        //查看律师是否通过认证
        if (mffluser.getLawyerInspect() != 1) {
            returnbean.setReturnBean("137");
            return returnbean;
        }

        if (mll.getState() != 1) {
            returnbean.setErrCode("119");
            returnbean.setMessage("当前状态，不允许进行律师发送邮件操作");
            return returnbean;
        }

        //合同寄送方信息
        MfflContract newmll = new MfflContract();
        newmll.setId(mll.getId());
        newmll.setLaywerConten(StringUtils.isEmpty(laywerConten) ? "" : laywerConten);
        newmll.setLawyerimage(StringUtils.isEmpty(lawyerimage) ? "" : lawyerimage);
        newmll.setState(3);//订单状态:0.发布成功1.已接单2.拒绝接单3.已发货4.完成交易5.已撤销订单6.超时接单撤销,自动退款7.已退款

        //设置时间多久后自动确认收货
        /*MfflService byId = mfflservicedao.getById((long) mll.getServiceId());
        long t1 = System.currentTimeMillis();
        long t2 = Long.valueOf(byId.getConfirmTime());
        Date date = new Date();
        date.setTime(t1 + t2);*/
        newmll.setConfirmTime(new Date()); //开始计时
        mfflContractDao.update(newmll);
        //推送
        MfflSystemMessagesImpl.sendMessage(publicService.MessageModel("[合同服务]服务律师已发送邮件", mll.getPayMerchantNumber()), mll.getServiceId().toString(), mll.getId().intValue(), mll.getUserid());

        return returnbean;
    }


    /**
     * @param type 0律师拨打用户，1用户拨打律师
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ReturnBean Phone(Integer type, Integer id) {
        ReturnBean returnBean = new ReturnBean();
        //合同是否存在
        MfflContract mll = mfflContractDao.getById(id.longValue());
        if (mll == null) {
            return new ReturnBean("201", "合同不存在");
        }

        if (type == 0) {
            returnBean.setReturnBean("200");
            returnBean.setDatas(mll.getNumber());
        } else {
            returnBean.setReturnBean("200");
            returnBean.setDatas(mll.getLawyerphone());
        }
        return returnBean;
    }


    /**
     * 用户确认合同确认完成
     *
     * @param lawyerletterId 合同id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ReturnBean ConfirmCompletion(Integer lawyerletterId) throws Exception {

        ReturnBean returnbean = new ReturnBean();
        //获取当前用户
        SysUser sysUser = UserUtil.getLoginUser();
        //合同是否存在

        MfflContract mll = mfflContractDao.getById(lawyerletterId.longValue());
        if (mll == null) {
            return new ReturnBean("201", "合同不存在");
        }

        if (mll.getUserid() != sysUser.getId().intValue()) {
            return new ReturnBean("201", "该合同不属于本用户");
        }

        //判断状态
        if (mll.getState() != 3) {
            returnbean.setErrCode("119");
            returnbean.setMessage("当前状态，不允许进行合同确认完成操作");
            return returnbean;
        }

        MfflUser userInfoAll = mffluserdao.getmffluser(mll.getServiceLawyerId());
        //查看律师是否通过认证
        if (userInfoAll.getLawyerInspect() != 1) {
            returnbean.setReturnBean("137");
            return returnbean;
        }

        try {
            //修改合同
            MfflContract mllt = new MfflContract();
            mllt.setId(mll.getId());
            mllt.setState(4);       //订单状态:0.发布成功1.已接单2.拒绝接单3.已发货4.完成交易5.已撤销订单6.超时接单撤销,自动退款7.已退款
            mfflContractDao.update(mllt);

            //获取订单信息
            MfflOrder mo = mfflOrderDao.getBypaymerchantnumber(mll.getPayMerchantNumber());
            //获取支入支出表---用户
            MfflProfit userProfit = mfflProfitDao.getByOrderId(mo.getId().intValue(), sysUser.getId().intValue());
            //获取支入支出表---律师
            MfflProfit lawyerProfit = mfflProfitDao.getByOrderId(mo.getId().intValue(), mll.getServiceLawyerId());

            //修改双方支付支出表--用户
            MfflProfit mp = new MfflProfit();
            mp.setId(userProfit.getId());
            mp.setUpdateTime(new Date());
            mfflProfitDao.update(mp);

            //修改双方支付支出表--律师
            MfflProfit mlp = new MfflProfit();
            mlp.setId(lawyerProfit.getId());
            mlp.setSettlement(1);          //0未结算，1已经算
            mlp.setUpdateTime(new Date());
            mfflProfitDao.update(mlp);

            //修改律师个人账户金额
            MfflUser mu = new MfflUser();
            mu.setId(userInfoAll.getId());
            mu.setMoney(ProjectUtil.addition(userInfoAll.getMoney(), mo.getMoney()));
            mu.setUpdateTime(new Date());
            mffluserdao.update(mu);

            //推送
            MfflSystemMessagesImpl.sendMessage(publicService.MessageModel("[合同服务]用户已确认完成", mll.getPayMerchantNumber()), mll.getServiceId().toString(), mll.getId().intValue(), mll.getServiceLawyerId());
            //增加服务人数
            LawyerservicepeoplenumberService.increaseLawyerservicepeoplenumber(userInfoAll.getId().intValue());
        } catch (Exception e) {
            e.printStackTrace();
            //returnbean.setReturnBean("105");
            //return returnbean;
            throw new Exception("合同完成服务异常");
        }
        returnbean.setReturnBean("200");
        return returnbean;
    }


    /**
     * 按照id获取合同
     *
     * @param id 合同id
     * @return
     */
    public ReturnBean<MfflContractVo> getIdlawyerletter(Integer id) {
        ReturnBean returnbean = new ReturnBean();
        //获取当前用户
        SysUser sysUser = UserUtil.getLoginUser();
        //合同是否存在
        MfflContractVo mll = mfflContractDao.getById(id.longValue());

        if (mll == null) {
            return new ReturnBean("201", "合同不存在");
        }

        //多图片处理图片处理
        if (!StringUtils.isEmpty(mll.getImageUrl())) {
            List<Map<String, Object>> maps = new ArrayList<>();
            String[] split = mll.getImageUrl().split(";");
            for (String time : split) {
                Map<String, Object> map = ProjectUtil.imageUrlAll(time);
                maps.add(map);
            }
            mll.setImageUrlAll(maps);
        }

        try {
            //查询律师信息
            mfflUserSimple lawyerinfo = mffluserdao.getUserInfoSimple(mll.getServiceLawyerId());
            //用户信息
            mfflUserSimple userinfo = mffluserdao.getUserInfoSimple(mll.getUserid());

            mll.setLaywerinfo(lawyerinfo);
            mll.setUserinfo(userinfo);
        } catch (Exception e) {
            e.printStackTrace();
            returnbean.setReturnBean("105");
            return returnbean;
        }
        returnbean.setReturnBean("200");
        returnbean.setDatas(mll);
        return returnbean;
    }


    /**
     * 取消发布
     *
     * @param id 合同id
     * @return
     */
    @Transactional
    public ReturnBean cancelLawyerletter(long id) throws Exception {
        ReturnBean returnbean = new ReturnBean();
        //获取当前用户
        SysUser sysUser = UserUtil.getLoginUser();
        //合同是否存在
        MfflContract mll = mfflContractDao.getById(id);
        if (mll == null) {
            return new ReturnBean("201", "合同不存在");
        }

        if (mll.getUserid() != sysUser.getId().intValue()) {
            return new ReturnBean("201", "该合同不属于本用户");
        }

        //判断当前状态
        if (mll.getState() != 0) {
            returnbean.setErrCode("119");
            returnbean.setMessage("当前状态，不允许进行退款操作");
            return returnbean;
        }
        //获取订单信息
        MfflOrder mo = mfflOrderDao.getBypaymerchantnumber(mll.getPayMerchantNumber());

        //获取支入支出表---用户
        MfflProfit userProfit = mfflProfitDao.getByOrderId(mo.getId().intValue(), sysUser.getId().intValue());

        //获取支入支出表---律师
        MfflProfit lawyerProfit = mfflProfitDao.getByOrderId(mo.getId().intValue(), mll.getServiceLawyerId());

        try {
            //未支付状态
            if (mo.getState() == 0) {
                //更新合同信息信息
                MfflContract mllr = new MfflContract();
                mllr.setId(id);
                //mllr.setDeleteState(0);
                mllr.setState(5);           //订单状态:0.发布成功1.已接单2.拒绝接单3.已发货4.完成交易5.已撤销订单6.超时接单撤销,自动退款7.已退款
                //mllr.setPayState(2);        //支付状态:0.待支付1.已支付2.已退款3.申请退款
                mllr.setUpdateTime(new Date());
                mfflContractDao.update(mllr);

                MfflOrder mffd = new MfflOrder();
                mffd.setId(mo.getId());
                Date date = new Date();
                mffd.setUpdtaeTime(date);
                mffd.setState(2);
                mffd.setDeleteStae(0);
                mfflOrderDao.update(mffd);
                return returnbean;
            }


            //退款操作
            ReturnBean returnBean = wxpayservice.weChatrefund(mo.getPayMerchantNumber(), null, "取消发布", 0);
            if (!"200".equals(returnBean.getErrCode())) {
                return returnBean;
            }

            //更新合同信息信息
            MfflContract mllr = new MfflContract();
            mllr.setId(id);
           //mllr.setDeleteState(0);
            mllr.setState(5);           //订单状态:0.发布成功1.已接单2.拒绝接单3.已发货4.完成交易5.已撤销订单6.超时接单撤销,自动退款7.已退款
            mllr.setPayState(2);        //支付状态:0.待支付1.已支付2.已退款3.申请退款
            mllr.setUpdateTime(new Date());
            mfflContractDao.update(mllr);


            //修改双方支付支出表--用户
            MfflProfit mp = new MfflProfit();
            mp.setId(userProfit.getId());
            mp.setSettlement(2);
            mp.setUpdateTime(new Date());
            mfflProfitDao.update(mp);

            //修改双方支付支出表--律师
            MfflProfit mlp = new MfflProfit();
            mlp.setId(lawyerProfit.getId());
            mlp.setSettlement(2);          //0未结算，1已经算 ， 2退款，3 申请退款
            mlp.setUpdateTime(new Date());
            mfflProfitDao.update(mlp);
            //推送
            MfflSystemMessagesImpl.sendMessage(publicService.MessageModel("[合同服务]用户撤销发布", mll.getPayMerchantNumber()), mll.getServiceId().toString(), mll.getId().intValue(), mll.getServiceLawyerId());
            return returnbean;
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("取消发布异常");
        }
    }


    /**
     * 申请退款操作
     *
     * @param id           合同id
     * @param refundreason 退款原因
     * @return
     */
    @Transactional
    public ReturnBean refund(Long id, String refundreason) throws Exception {
        ReturnBean returnbean = new ReturnBean();
        //获取当前用户
        SysUser sysUser = UserUtil.getLoginUser();
        //合同是否存在
        MfflContract mll = mfflContractDao.getById(id);
        if (mll == null) {
            return new ReturnBean("201", "合同不存在");
        }

        if (mll.getUserid() != sysUser.getId().intValue()) {
            return new ReturnBean("201", "合同不属于本用户");
        }

        //判断当前状态
        if ((mll.getState() == 0 || mll.getState() == 3) && mll.getPayState() == 1) {
            returnbean.setErrCode("119");
            returnbean.setMessage("当前状态，不允许进行申请退款操作");
            return returnbean;
        }

        try {


            //更新合同信息
            MfflContract mllr = new MfflContract();
            mllr.setId(id);
            // mllr.setState(5);    //订单状态:0.发布成功1.已接单2.拒绝接单3.已发货4.完成交易5.已撤销订单6.超时接单撤销,自动退款7.已退款")
            mllr.setPayState(3);    //支付状态:0.待支付1.已支付2.已退款3.申请退款")
            mllr.setUpdateTime(new Date());
            mfflContractDao.update(mllr);

            //获取订单信息
            MfflOrder mo = mfflOrderDao.getBypaymerchantnumber(mll.getPayMerchantNumber());

            //获取支入支出表---用户
            MfflProfit userProfit = mfflProfitDao.getByOrderId(mo.getId().intValue(), sysUser.getId().intValue());

            //获取支入支出表---律师
            MfflProfit lawyerProfit = mfflProfitDao.getByOrderId(mo.getId().intValue(), mll.getServiceLawyerId());

            //修改双方支付支出表--用户
            MfflProfit mp = new MfflProfit();
            mp.setId(userProfit.getId());
            mp.setSettlement(3);//0未结算，1已经算 ， 2退款，3 申请退款
            mp.setUpdateTime(new Date());
            mfflProfitDao.update(mp);  //获取支入支出表---用户

            //修改双方支付支出表--律师
            MfflProfit mlp = new MfflProfit();
            mlp.setId(lawyerProfit.getId());
            mlp.setSettlement(3);//0未结算，1已经算 ， 2退款，3 申请退款
            mlp.setUpdateTime(new Date());
            mfflProfitDao.update(mlp);

            //修改订单信息
            MfflOrder mfflOrder = new MfflOrder();
            mfflOrder.setId(mo.getId());
            mfflOrder.setUpdtaeTime(new Date());
            mfflOrder.setState(4);//0待支付，1支付，2退款 , 4申请退款
            mfflOrderDao.update(mfflOrder);

            //新增退款信息
            MfflRefund refund = new MfflRefund();
            refund.setUserid(mo.getUserid());
            refund.setImplementid(0);
            refund.setOrderid(mo.getId().intValue());
            refund.setPaynumber(mo.getPayNumber());
            refund.setPaymerchantnumber(mo.getPayMerchantNumber());
            refund.setRefundnumber(mo.getPayNumber());
            refund.setRefundreason(refundreason);
            refund.setRefundstate(0);
            refund.setMoney(mo.getMoney());
            refund.setActualamount(mo.getMoney());
            Date date = new Date();
            refund.setRefundtime(date);
            refund.setCreateTime(date);
            refund.setUpdateTime(date);
            refund.setConfirmrefundtim(date);
            refund.setRefundname(mo.getServiceName());
            mfflRefundDao.save(refund);
            //推送
            MfflSystemMessagesImpl.sendMessage(publicService.MessageModel("[合同服务]用户申请退款", mll.getPayMerchantNumber()), mll.getServiceId().toString(), mll.getId().intValue(), mll.getServiceLawyerId());
            return returnbean;
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("申请退款异常,请稍后再试");
        }
    }


    /**
     * 取消申请退款
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ReturnBean cancelRefund(Long id) throws Exception {
        ReturnBean returnbean = new ReturnBean();

        //获取当前用户
        SysUser sysUser = UserUtil.getLoginUser();
        //合同是否存在
        MfflContract mll = mfflContractDao.getById(id);
        if (mll == null) {
            return new ReturnBean("201", "合同不存在");
        }

        if (mll.getUserid() != sysUser.getId().intValue()) {
            return new ReturnBean("201", "合同不属于本用户");
        }

        //判断当前状态状态
        if (mll.getPayState() != 3) {
            returnbean.setErrCode("119");
            returnbean.setMessage("当前状态，不允许进行取消申请退款操作");
            return returnbean;
        }
        try {
            //更新合同信息
            MfflContract mllr = new MfflContract();
            mllr.setId(id);
            // mllr.setState(5);       //订单状态(0发布需求,1律师沟通,2寄送律件,3完成服务,4撤销发布,5申请退款)
            mllr.setPayState(1);       //支付状态:0.待支付1.已支付2.已退款3.申请退款")
            mllr.setUpdateTime(new Date());
            mfflContractDao.update(mllr);

            //获取订单信息
            MfflOrder mo = mfflOrderDao.getBypaymerchantnumber(mll.getPayMerchantNumber());

            //获取支入支出表---用户
            MfflProfit userProfit = mfflProfitDao.getByOrderId(mo.getId().intValue(), sysUser.getId().intValue());

            //获取支入支出表---律师
            MfflProfit lawyerProfit = mfflProfitDao.getByOrderId(mo.getId().intValue(), mll.getServiceLawyerId());


            Date date = new Date();
            //修改双方支付支出表--用户
            MfflProfit mp = new MfflProfit();
            mp.setId(userProfit.getId());
            mp.setSettlement(1);//0未结算，1已经算 ， 2退款，3 申请退款
            mp.setUpdateTime(date);
            mfflProfitDao.update(mp);  //获取支入支出表---用户

            //修改双方支付支出表--律师
            MfflProfit mlp = new MfflProfit();
            mlp.setId(lawyerProfit.getId());
            mlp.setSettlement(0);//0未结算，1已经算 ， 2退款，3 申请退款
            mlp.setUpdateTime(date);
            mfflProfitDao.update(mlp);

            //修改订单信息
            MfflOrder mfflOrder = new MfflOrder();
            mfflOrder.setId(mo.getId());
            mfflOrder.setUpdtaeTime(date);
            mfflOrder.setState(1);//0待支付，1支付，2退款 , 4申请退款
            mfflOrderDao.update(mfflOrder);

            //新增退款信息
            MfflRefund byorderId = mfflRefundDao.getByorderId(mo.getId());
            MfflRefund refund = new MfflRefund();
            refund.setId(byorderId.getId());
            refund.setRefundstate(2);
            refund.setUpdateTime(new Date());
            mfflRefundDao.update(refund);
            //推送
            MfflSystemMessagesImpl.sendMessage(publicService.MessageModel("[合同服务]用户取消申请退款", mll.getPayMerchantNumber()), mll.getServiceId().toString(), mll.getId().intValue(), mll.getServiceLawyerId());
            return returnbean;
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("取消申请退款异常");
        }
    }


    /**
     * 律师拒绝接受合同服务
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ReturnBean refuse(Integer id) throws Exception {
        try {
            ReturnBean returnbean = new ReturnBean();
            //获取当前用户
            SysUser sysUser = UserUtil.getLoginUser();

            //律师函是否存在
            MfflContract mll = mfflContractDao.getById(id.longValue());
            if (mll == null) {
                return new ReturnBean("201", "合同不存在");
            }

            //判断当前律师是否，是负责当前合同的律师
            if (mll.getServiceLawyerId() != sysUser.getId().intValue()) {
                return new ReturnBean("201", "当前律师不是,负责此合同的律师");
            }

            //判断合同状态
            if (mll.getState() != 0 && mll.getPayState() == 1) {
                returnbean.setErrCode("119");
                returnbean.setMessage("当前状态，不允许进行拒绝接受合同服务操作");
                return returnbean;
            }

            //获取订单信息
            MfflOrder mo = mfflOrderDao.getBypaymerchantnumber(mll.getPayMerchantNumber());

            //退款操作
            ReturnBean returnBean = wxpayservice.weChatrefund(mo.getPayMerchantNumber(), null, "律师拒绝服务", 0);
            if (!"200".equals(returnBean.getErrCode())) {
                return returnBean;
            }


            //更新合同信息
            MfflContract mllr = new MfflContract();
            mllr.setId(id.longValue());
            mllr.setState(2);           //订单状态:0.发布成功1.已接单2.拒绝接单3.已发货4.完成交易5.已撤销订单6.超时接单撤销,自动退款7.已退款
            mllr.setPayState(2);        //支付状态:0.待支付1.已支付2.已退款3.申请退款
            mllr.setUpdateTime(new Date());
            mfflContractDao.update(mllr);


            //获取支入支出表---用户
            MfflProfit userProfit = mfflProfitDao.getByOrderId(mo.getId().intValue(), mll.getUserid().intValue());

            //获取支入支出表---律师
            MfflProfit lawyerProfit = mfflProfitDao.getByOrderId(mo.getId().intValue(), mll.getServiceLawyerId());


            //修改双方支付支出表--用户
            MfflProfit mp = new MfflProfit();
            mp.setId(userProfit.getId());
            mp.setSettlement(2);
            mp.setUpdateTime(new Date());
            mfflProfitDao.update(mp);

            //修改双方支付支出表--律师
            MfflProfit mlp = new MfflProfit();
            mlp.setId(lawyerProfit.getId());
            mlp.setSettlement(2);          //0未结算，1已经算 ， 2退款，3 申请退款
            mlp.setUpdateTime(new Date());
            mfflProfitDao.update(mlp);
            //推送
            MfflSystemMessagesImpl.sendMessage(publicService.MessageModel("[合同服务]律师拒绝服务", mll.getPayMerchantNumber()), mll.getServiceId().toString(), mll.getId().intValue(), mll.getUserid());
            return returnbean;
        } catch (Exception e) {
            throw new Exception("异常错误");
        }
    }


    /**
     * 评论
     *
     * @param comment 评论内容
     * @param rank    评论级别 1好评 2中评 3差评
     * @param id      合同id
     * @return
     */
    @Transactional
    public ReturnBean comment(String comment, Integer rank, Integer id) {
        ReturnBean returnBean = new ReturnBean();
        //获取当前用户
        SysUser sysUser = UserUtil.getLoginUser();
        //合同是否存在
        MfflContract mll = mfflContractDao.getById(id.longValue());
        if (mll == null) {
            return new ReturnBean("201", "合同不存在");
        }

        if (mll.getUserid() != sysUser.getId().intValue()) {
            return new ReturnBean("201", "合同不属于本用户");
        }

        if (mll.getCommentState() == 1) {
            return new ReturnBean("201", "已评论过了，无需重复评论");
        }

        if (mll.getState() != 4) {
            return new ReturnBean("201", "订单不是完成状态，无法评论");
        }

        MfflContract mllr = new MfflContract();
        mllr.setId(mll.getId());
        mllr.setCommentState(1);    //是否0未评论1评论
        mllr.setUpdateTime(new Date());
        mfflContractDao.update(mllr);

        //新增评论
        mfflLawyercommentservice.LawyerComment(comment, rank, mll.getUserid(), mll.getServiceLawyerId(), mll.getType());
        //推送
       //MfflSystemMessagesImpl.sendMessage(publicService.MessageModel("[合同服务]用户已评论", mll.getPayMerchantNumber()), mll.getServiceId().toString(), mll.getId().intValue(), mll.getServiceLawyerId());
        return returnBean;
    }

    /**
     * 律师确认接单
     *
     * @param id 合同id
     * @return
     */
    public ReturnBean confirm(Integer id) {
        ReturnBean returnBean = new ReturnBean();
        //获取当前用户
        SysUser sysUser = UserUtil.getLoginUser();
        //合同是否存在
        MfflContract mll = mfflContractDao.getById(id.longValue());
        if (mll == null) {
            return new ReturnBean("201", "合同不存在");
        }
        //判断当前律师是否，是负责当前合同的律师
        if (mll.getServiceLawyerId() != sysUser.getId().intValue()) {
            return new ReturnBean("201", "当前律师不是,负责此合同的律师");
        }

        if (mll.getState() != 0) {
            returnBean.setErrCode("119");
            returnBean.setMessage("当前状态，不允许进行律师确认接单操作");
            return returnBean;
        }

        SysUser byId1 = userdao.getById(sysUser.getId());
        MfflUser byId = mffluserdao.getByUserId(byId1.getId());

        //查看律师是否通过认证
        if (byId.getLawyerInspect() != 1) {
            returnBean.setReturnBean("137");
            return returnBean;
        }

        MfflContract mllr = new MfflContract();
        mllr.setId(mll.getId());
        mllr.setState(1);    //订单状态:0.发布成功1.已接单2.拒绝接单3.已发货4.完成交易5.已撤销订单6.超时接单撤销,自动退款7.已退款
        mllr.setUpdateTime(new Date());
        mfflContractDao.update(mllr);

        //推送
        MfflSystemMessagesImpl.sendMessage(publicService.MessageModel("[合同服务]律师确认接单", mll.getPayMerchantNumber()), mll.getServiceId().toString(), mll.getId().intValue(), mll.getUserid());
        return returnBean;
    }

    /**
     * 关系合同同时关闭订单
     *
     * @param id 咨询id
     */
    @Transactional
    public void delLetterAndOrder(Long id) {
        mfflContractDao.delete(id);
        mfflOrderDao.deleteOrderByProductId(id);
    }

    /**
     * 获取定时任务要处理的数据
     *
     * @param ContractAudit_ConfirmTime         【合同审核】用户未点击完成超时时间。
     * @param ContractAudit_RefuseTime          【合同审核】律师超时未接受时间。
     * @param ContractCustomization_ConfirmTime 【合同定制】用户未点击完成超时时间。
     * @param ContractCustomization_RefuseTime  【合同定制】律师超时未接受时间。
     * @return
     */
    public List<MfflContract> getContractAuditTimerTaskData(Long ContractAudit_ConfirmTime, Long ContractAudit_RefuseTime, Long ContractCustomization_ConfirmTime, Long ContractCustomization_RefuseTime) {
        return mfflContractDao.getTimerTaskData(ContractAudit_ConfirmTime, ContractAudit_RefuseTime, ContractCustomization_ConfirmTime, ContractCustomization_RefuseTime);
    }


    /**
     * 修改
     *
     * @param mfflContract
     * @return
     */
    public int update(MfflContract mfflContract) {
        return mfflContractDao.update(mfflContract);
    }
}
